package top.lyc829.mymusic.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.lzx.starrysky.StarrySky
import top.lyc829.mymusic.MyApp
import top.lyc829.mymusic.ext.showToast
import top.lyc829.mymusic.viewmodel.AppViewModel
import top.lyc829.mymusic.viewmodel.EventViewModel

abstract class BaseFragment<VM : BaseViewModel, VB: ViewBinding> : Fragment() {

    private lateinit var _binding: VB
    protected val binding get() = _binding

    lateinit var mViewModel : VM
    val appViewModel : AppViewModel by activityViewModels()

    val eventViewModel: EventViewModel by lazy { ViewModelProvider(MyApp.context as MyApp).get(EventViewModel::class.java) }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = getBinding(inflater)
        return _binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mViewModel = getViewModel()
        beforeInit()
        initView(savedInstanceState)
        initClickListener()
        createObserver()
        initData()

        mViewModel.errorLiveData.observe(viewLifecycleOwner) {
            it.message?.let { it1 -> showToast(it1) }
        }
    }

    private fun beforeInit() {
        StarrySky.with().playbackState().observe(context as LifecycleOwner) {
            eventViewModel.updatePlayBackState(it)
        }
    }

    abstract fun getViewModel(): VM

    abstract fun getBinding(inflater: LayoutInflater): VB


    /**
     * 初始化view
     */
    abstract fun initView(savedInstanceState: Bundle?)

    abstract fun initClickListener()

    abstract fun createObserver()

    abstract fun initData()

}